package com.zzgc.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.zzgc.common.entity.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 合并多个pdf 到一个pdf
 *
 * @Author:
 * @CreateTime: 2023-01-05  10:33
 * @Description:
 * @Version: 1.0
 */
public class MergePdfFiles {
    private static final Logger logger = LoggerFactory.getLogger(MergePdfFiles.class);

    public static void main(String[] args) throws IOException {
        List<BufferedImage> list = new ArrayList<>();
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201209133422.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201212023849.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\42082220120915482X.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201308295822.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201211275825.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201209045860.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201304250627.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411623201303296837.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201302070614.jpg")));
        list.add(ImageIO.read(new File("D:\\lgl\\data\\411621201301250672.jpg")));

//        List<List<BufferedImage>> lists = mySubList(list);
//        for (int i = 0; i < lists.size(); i++) {
//            BufferedImage image = mergeImage(true, lists.get(i));
//            ImageIO.write(image, "png", new File("D:\\lgl\\data\\test" + i + ".png"));
//        }
    }

    public static List<List<Student>> mySubList(List<Student> list) {
        int size = list.size();
        int total = 6;
        List<List<Student>> arrayList = new ArrayList<>();
        for (int i = 0; i < size; i += total) {
            List<Student> list1 = null;
            if (total + i > size) {
                list1 = list.subList(i, size);
            } else {
                list1 = list.subList(i, total + i);
            }
            arrayList.add(list1);
        }
        return arrayList;
    }

    /**
     * 合并任数量的图片成一张图片
     *
     * @param isHorizontal true代表水平合并，fasle代表垂直合并
     * @param imgs         待合并的图片数组
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) {
        // 生成新图片
        BufferedImage destImage = null;
        // 计算新图片的长和高
//        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
//        // 获取总长、总宽、最长、最宽
//        for (int i = 0; i < imgs.length; i++) {
//            BufferedImage img = imgs[i];
//            allw += img.getWidth();
//            allh += img.getHeight();
//            if (img.getWidth() > allwMax) {
//                allwMax = img.getWidth();
//            }
//            if (img.getHeight() > allhMax) {
//                allhMax = img.getHeight();
//            }
//        }
        // 创建新图片
//        if (isHorizontal) {
//            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
//        } else {
//            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
//        }
        destImage = new BufferedImage(imgs.get(0).getWidth() * 2 + 10, imgs.get(0).getHeight() * 3 + 20, BufferedImage.TYPE_INT_RGB);
        // 获取Graphics2D
        Graphics2D g2d = destImage.createGraphics();
        // 设置透明背景, 生成png文件, jpg不是透明的
        destImage = g2d.getDeviceConfiguration().createCompatibleImage(imgs.get(0).getWidth() * 2 + 10, imgs.get(0).getHeight() * 3 + 20, Transparency.TRANSLUCENT);
        //释放对象
        g2d.dispose();

        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (int i = 1; i < imgs.size() + 1; i++) {
            if (i % 2 == 1) {
                isHorizontal = false;
            } else {
                isHorizontal = true;
            }
            BufferedImage img = imgs.get(i - 1);
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                wx = h1 + 10;
                destImage.setRGB(wx, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
                wy += h1 + 10;
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }
        }
        return destImage;
    }

    /**
     * 将多个pdf合并成一个pdf文件
     *
     * @param pdfFilesPath  全路径
     * @param mergeFilePath 全路径
     */
    public static Boolean mergePdf(List<String> pdfFilesPath, String mergeFilePath) {
        Document document = null;
        ByteArrayOutputStream os = null;
        try {
            // 获取纸张大小并实例化一个新的空文档, 例如 A5 纸
            document = new Document();
//            document = new Document(new PdfReader(pdfFilesPath.get(0)).getPageSize(1));
            os = new ByteArrayOutputStream();
            // 实例化复制工具
            final PdfCopy copy = new PdfCopy(document, new FileOutputStream(mergeFilePath));
            // 打开文档准备写入内容
            document.open();
            // 循环所有pdf文件
            for (String s : pdfFilesPath) {
                // 读取pdf
                PdfReader reader = new PdfReader(new FileInputStream(s));
//                final PdfReader reader = new PdfReader(new FileInputStream(s));
                PdfImportedPage page = copy.getImportedPage(reader, 1);
                copy.addPage(page);
//                // 获取页数
//                final int numberOfPages = reader.getNumberOfPages();
//                // pdf的所有页, 从第1页开始遍历, 这里要注意不是0
//                for (int i = 1; i <= numberOfPages; i++) {
//                    document.newPage();
//                    // 把第 i 页读取出来
//                    final PdfImportedPage page = copy.getImportedPage(reader, i);
//                    // 把读取出来的页追加进输出文件里
//                    copy.addPage(page);
//                }
                reader.close();

            }
            //输出到指定目录文件中
//            FileOutputStream fos = new FileOutputStream(mergeFilePath);
//            fos.write(os.toByteArray());
//            fos.close();
            copy.close();

            return true;
        } catch (IOException | DocumentException e) {
            logger.info("Pdf合并发生异常", e);
            return false;
        } finally {
            if (document != null) {
                document.close();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.info("Pdf合并发生异常", e);
                }
            }
        }
    }
}
